<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入名字" />
      <el-button v-permission="['GET /admin/seat/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/seat/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="expand">
        <template slot-scope="props">
          <div v-for="item in props.row.seatDetailList" :key="item.id" class="order-goods">
            <div class="name">
              预定日期：{{ item.orderDay }}  {{ item.orderTime }}
            </div>
            <div class="name">
              预订人：{{ item.orderNick }}
            </div>
            <div class="name">
              联系方式：{{ item.orderPhone }}
            </div>

          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" prop="id" sortable />
      <el-table-column align="center" label="类型" prop="type" sortable />
      <el-table-column align="center" label="座位编号" prop="seatNo" sortable />
      <el-table-column align="center" label="最小人数" prop="minCount" sortable />
      <el-table-column align="center" label="最多人数" prop="maxCount" sortable />
      <el-table-column align="center" label="特色" prop="characteristic" />
      <el-table-column align="center" property="iconUrl" label="图片">
        <template slot-scope="scope" >
          <img v-if="scope.row.images && scope.row.images.length > 0" :src="scope.row.images[0]" width="40">
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/seat/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/seat/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="dataForm.type">
            <el-radio label="大厅">大厅</el-radio>
            <el-radio label="包间">包间</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="座位编号" prop="seatNo">
          <el-input v-model="dataForm.seatNo" />
        </el-form-item>
        <el-form-item label="最小人数" prop="minCount">
          <el-input v-model.number="dataForm.minCount" />
        </el-form-item>
        <el-form-item label="最多人数" prop="maxCount">
          <el-input v-model.number="dataForm.maxCount" />
        </el-form-item>
        <el-form-item label="图片列表" prop="images">
          <el-upload
            :action="uploadPath"
            :limit="5"
            :headers="headers"
            :file-list="galleryFileList"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="特色" >
          <el-input
            v-model="dataForm.characteristic"
            type="textarea"
            placeholder="比如: 靠窗 圆桌等"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
.order-goods {
  display: flex;
  justify-content: space-around;
  justify-items: center;
  align-items:center;
  padding: 6px 0;
}
.name {
  width: 200px;
}
</style>

<script>
import { listSeat, createSeat, updateSeat, deleteSeat } from '@/api/seat'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Seat',
  components: { Pagination },
  data() {
    return {
      galleryFileList: [],
      uploadPath,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        content: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        type: '',
        minCount: '',
        maxCount: '',
        status: 1,
        orderTime: '',
        orderDay: '',
        storeId: '',
        images: [],
        characteristic:""
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        seatNo: [
          { required: true, message: '座位编号不能为空', trigger: 'blur' }
        ],
        minCount: [
          { required: true, message: '最小人数不能为空', trigger: 'blur' }
        ],
        maxCount: [
          { required: true, message: '最多人数不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '房间状态', trigger: 'blur' }
        ],
        orderTime: [
          { required: true, message: '预定时间   时:分不能为空', trigger: 'blur' }
        ],
        orderDay: [
          { required: true, message: '预定日期 年月日不能为空', trigger: 'blur' }
        ],
        storeId: [
          { required: true, message: '商家ID不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        if (this.dataForm.images) {
          this.dataForm.images.push(response.data.url)
        }
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.dataForm.images.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.dataForm.images[i] === url) {
          this.dataForm.images.splice(i, 1)
        }
      }
    }
    ,
    statusFormatter(scope) {
      if (scope.row.status == 1) {
        return "<span style='color:green'>空座</span>"
      }
      if (scope.row.status == 2) {
        return "<span style='color:pink'>预约</span>"
      }
      return "<span style='color:red'>已入座</span>"
    },
    getList() {
      this.listLoading = true
      listSeat(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        type: '大厅',
        minCount: undefined,
        maxCount: undefined,
        status: 1,
        orderTime: undefined,
        orderDay: undefined,
        storeId: undefined,
        images: [],
        characteristic:""
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadUrl: function(response) {
      this.dataForm.url = response.data.url
    },
    checkFileSize: function(file) {
      if (file.size > 1048576) {
        this.$message.error(file.name + '文件大于1024KB，请选择小于1024KB大小的图片')
        return false
      }
      return true
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createSeat(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      if(!this.dataForm.images)
      {
        this.dataForm.images=[];
      }
      this.galleryFileList = []
      if (this.dataForm.images) {
        for (var i = 0; i < this.dataForm.images.length; i++) {
          this.galleryFileList.push({
            url: this.dataForm.images[i]
          })
        }
      }


      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateSeat(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新广告成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteSeat(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          this.getList()
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '类型',
          '最小人数',
          '最多人数',
          '房间状态 1:空座   2:预定   3:已入座',
          '预定时间   时:分',
          '预定日期 年月日',
          '商家ID'
        ]
        const filterVal = [
          'type',
          'minCount',
          'maxCount',
          'status',
          'orderTime',
          'orderDay',
          'storeId'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '广告信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
